package fischl.web;

import fi.iki.elonen.NanoHTTPD;
import fischl.Global;
import fischl.Platform;
import fischl.VideoMarker;
import fischl.log.Log;
import fischl.log.LogFactory;
import fischl.model.VideoModel;

import java.util.HashMap;
import java.util.Map;

import static fi.iki.elonen.NanoHTTPD.newFixedLengthResponse;

public class MarkerHandler implements RouteHandler {
  private static final Log log = LogFactory.get("marker");

  @Override
  public NanoHTTPD.Response handle(NanoHTTPD.IHTTPSession session) {
    if(!"/processed".equals(session.getUri())) return null;

    String vid = session.getParms().get("vid");
    boolean status = Boolean.parseBoolean(session.getParms().get("value"));
    VideoModel model = Platform.current().getVideoModelByVid(vid);
    Map<String, Object> json = new HashMap<>();
    if (model == null) {
      log.w("Could not find video: " + vid);
      json.put("code", 1);
      json.put("msg", "找不到video:" + vid);
    } else {
      if (status == model.isProcessed) {
        log.w("model process state will not be changed");
        json.put("code", 2);
        json.put("msg", "状态没有改变");
      } else {
        model.isProcessed = status;
        if (model.isProcessed) {
          VideoMarker.mark(model);
        }
        json.put("code", 0);
        json.put("msg", "ok");
      }
    }
    json.put("vid", vid);
    String jsonText = Global.gson().toJson(json);
    return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "application/json", jsonText);
  }
}
